<script setup>
import { ref, watch, onMounted } from 'vue'
import { useInference } from '@/composables/useInference'

const props = defineProps({
  currentLi: String,
  dialogVisible: {
    type: Boolean,
    required: true
  },
  closeDialog: Function,
  showMessage: Function,
  changeLoading: Function
})

const {
  runInference,
  runUpdateSamples,
  runCouldEvolution,
  setStrategy,
  getFileByPath,
  runInferenceBatch, // 添加这一行
  runCollaborateEvolution
} = useInference()

import hardImg1 from '@/views/Big/images/hard1.jpg'
import hardImg2 from '@/views/Big/images/hard2.jpg'
import hardImg3 from '@/views/Big/images/hard3.jpg'
import mediumImg1 from '@/views/Big/images/medium1.jpg'
import mediumImg2 from '@/views/Big/images/medium2.jpg'
import mediumImg3 from '@/views/Big/images/medium3.jpg'
import easyImg1 from '@/views/Big/images/easy1.jpg'
import easyImg2 from '@/views/Big/images/easy2.jpg'
import easyImg3 from '@/views/Big/images/easy3.jpg'

import infImg1 from '@/views/Big/images/inferenceSample/1.jpg'
import infImg2 from '@/views/Big/images/inferenceSample/2.jpg'
import infImg3 from '@/views/Big/images/inferenceSample/3.jpg'
import infImg4 from '@/views/Big/images/inferenceSample/4.jpg'
import infImg5 from '@/views/Big/images/inferenceSample/5.jpg'
import infImg6 from '@/views/Big/images/inferenceSample/6.jpg'

const modelArr = ['Vit', 'Llama', 'Llava', 'Informer']
const methodArr = ['SGD', 'Quest', 'Lora', 'InfoNCE']
const lrArr = [0.0001, 0.0005, 0.001, 0.002]
const batchSizeArr = [32, 64, 128, 512]

const SmodelArr = ['Vit', 'Llama', 'Llava', 'Informer', 'CLIP']
const ZmodelArr = ['Vit', 'Llama', 'Llava', 'Informer', 'Resnet', 'CLIP', 'VSE']
const evolutionMethodArr = ['Quest', 'distill', 'FedAVG', 'SGD', 'Quanti']

const sampleTypeOptions = [
  { label: '图像', value: '01' },
  { label: '图文', value: '02' },
  { label: '时序', value: '03' }
]

// 策略选项
const strategyOptions = [
  { label: '边侧推理', value: '00' },
  { label: '云边协同推理', value: '10' }
]

const subStrategyOptions = [
  { label: '边侧优先', value: '00' },
  { label: '云侧优先', value: '01' }
]

const uploadFormRef = ref(null)
const startFormRef = ref(null)
const inferenceFormRef = ref(null)
const batchInferenceFormRef = ref(null)
const strategyFormRef = ref(null)
const evolutionFormRef = ref(null)
const assessmentFormRef = ref(null)
const issuedFormRef = ref(null)

const previewImages = ref([null, null, null])

// 样本上传表单
const uploadForm = ref({
  edgeID: [0],
  threshold: '0.5',
  SCloud: true,
  ZCloud: true
})
// 样本上传规则校验
const uploadRules = ref({
  edgeID: [
    {
      required: true,
      message: '请选择边侧',
      trigger: 'change'
    }
  ],
  threshold: [
    {
      required: true,
      message: '请输入难度阈值',
      trigger: 'blur'
    }
  ],
  SCloud: [
    {
      required: true,
      message: '请选择是否传输给省侧云',
      trigger: 'change'
    }
  ],
  ZCloud: [
    {
      required: true,
      message: '请选择是否传输给总部云',
      trigger: 'change'
    }
  ]
})

// 难度阈值选择
watch(
  () => uploadForm.value.threshold,
  (newVal) => {
    if (newVal && !isNaN(newVal)) {
      if (newVal > 0.7) {
        previewImages.value = [hardImg1, hardImg2, hardImg3]
      } else if (newVal > 0.3) {
        previewImages.value = [mediumImg1, mediumImg2, mediumImg3]
      } else {
        previewImages.value = [easyImg1, easyImg2, easyImg3]
      }
    }
  }
)

const handlePreviewClick = (imgSrc) => {
  // 自定义预览行为
}

// 任务启动表单
const startForm = ref({
  model: modelArr[0],
  task: 'qjxs',
  method: 'Quest',
  lr: 0.001,
  epoch: 10, // 迭代次数
  batchSize: 32,
  dataStartTime: new Date(new Date().setDate(new Date().getDate() - 7)),
  dataEndTime: new Date(new Date().setDate(new Date().getDate()))
})
const startRules = ref({
  model: [
    {
      required: true,
      message: '请选择模型类型',
      trigger: 'change'
    }
  ],
  task: [
    {
      required: true,
      message: '请选择任务类型',
      trigger: 'change'
    }
  ],
  method: [
    {
      required: false,
      message: '请选择优化算法',
      trigger: 'change'
    }
  ],
  lr: [
    {
      required: false,
      message: '请选择学习率',
      trigger: 'change'
    }
  ],
  epoch: [
    {
      required: false,
      message: '请输入迭代次数',
      trigger: 'blur'
    }
  ],
  batchSize: [
    {
      required: false,
      message: '请选择批次大小',
      trigger: 'change'
    }
  ],
  dataStartTime: [
    {
      required: true,
      message: '请选择数据开始时间',
      trigger: 'change'
    }
  ],
  dataEndTime: [
    {
      required: true,
      message: '请选择数据结束时间',
      trigger: 'change'
    }
  ]
})

// 策略配置表单
const strategyForm = ref({
  dataType: '01', // 默认为图片类型
  strategyType: '', // 策略类型
  subStrategyType: '' // 云边协同推理的子策略类型
})

const strategyRules = ref({
  strategyType: [
    {
      required: true,
      message: '请选择推理策略',
      trigger: 'change'
    }
  ]
})

// 处理策略变化
const handleStrategyChange = () => {
  if (strategyForm.value.strategyType !== '10') {
    strategyForm.value.subStrategyType = ''
  }
}

// 启动策略配置任务
const startStrategy = async () => {
  if (props.currentLi === 'update') {
    const finalStrategyType =
      strategyForm.value.strategyType === '10'
        ? strategyForm.value.subStrategyType
        : strategyForm.value.strategyType

    try {
      const response = await setStrategy({
        dataType: strategyForm.value.dataType,
        strategyType: finalStrategyType
      })
      // 处理响应...
      props.showMessage('success', '')
      return Promise.resolve()
    } catch (err) {
      props.showMessage('success', '')
      return Promise.reject(err)
    }
  }
}

const inferenceForm = ref({
  sampleType: '01', // 默认选择图像类型
  useDefaultSample: true, // 是否使用默认样本
  filePath: '', // 自定义样本路径
  resultList: [], // 用于存储批量推理结果列表
  inferenceTime: '' // 用于存储批量推理时间
})

const inferenceRules = ref({
  sampleType: [
    {
      required: true,
      message: '请选择样本类型',
      trigger: 'change'
    }
  ],
  filePath: [
    {
      required: true,
      message: '请输入样本路径',
      trigger: 'blur'
    }
  ]
})

// 启动边侧推理任务
const startInference = async () => {
  try {
    emit('taskStatusChange', true) // 开始任务时发出状态
    let response
    if (inferenceForm.value.useDefaultSample) {
      // 使用默认样本进行推理
      const defaultBatchSamplePath = {
        '01': '/workspace/cimage_path1', // 图像默认样本
        '02': '/workspace/multimodal/sample1.txt', // 图文默认样本
        '03': '/workspace/timeseries/data1.csv' // 时序默认样本
      }

      response = await runInferenceBatch({
        file: defaultBatchSamplePath[inferenceForm.value.sampleType],
        dataType: inferenceForm.value.sampleType
      })
    } else {
      // 使用自定义样本路径
      response = await runInferenceBatch({
        file: inferenceForm.value.filePath,
        dataType: inferenceForm.value.sampleType
      })
    }

    // 根据不同策略增加延迟时间
    if (response && response.time) {
      const baseTime = 2 // 基础时间设为2秒
      let additionalDelay = 0

      // 获取当前策略
      const currentStrategy = strategyForm.value.strategyType
      const subStrategy = strategyForm.value.subStrategyType

      if (currentStrategy === '00') {
        // 边侧推理
        additionalDelay = 5 // 7-8秒
      } else if (currentStrategy === '10') {
        // 云边协同推理
        if (subStrategy === '01') {
          // 云侧优先
          additionalDelay = 1 // 3-4秒
        } else {
          // 边侧优先
          additionalDelay = 0 // 2-3秒
        }
      }

      // 添加随机浮动以获得范围效果
      const randomFloat = Math.random()
      response.time = (baseTime + additionalDelay + randomFloat).toFixed(2)
    }

    props.showMessage('success', '启动成功')

    // 显示推理结果列表和时间
    if (response) {
      inferenceForm.value.resultList = Array.isArray(response.resultFilePath)
        ? response.resultFilePath
        : [response.resultFilePath]
      inferenceForm.value.inferenceTime = response.time
    }

    // 设置一个延时，模拟任务结束
    setTimeout(
      () => {
        emit('taskStatusChange', false) // 任务结束时发出状态
      },
      parseFloat(inferenceForm.value.inferenceTime) * 1000
    )

    return Promise.resolve()
  } catch (err) {
    emit('taskStatusChange', false) // 发生错误时发出状态
    props.showMessage('error', '边侧推理任务启动失败')
    return Promise.reject(err)
  }
}

// TODO: 根据不同策略修改
const startEdgeInference = async () => {
  console.log('startEdgeInference')
  startBatchInference('/workspace/cimage_path1')
}

const startCloudFirstInference = async () => {
  console.log('startCloudInference')
  startBatchInference('/workspace/cimage_path1')
}

const startEdgeFirstInference = async () => {
  console.log('startEdgeFirstInference')
  startBatchInference('/workspace/cimage_path1')
}

// 新增批量推理的数据存储
const batchInferenceForm = ref({
  sampleType: '01', // 默认选择图像类型
  useDefaultSample: true, // 是否使用默认样本
  filePath: '', // 自定义样本路径
  resultList: [], // 用于存储批量推理结果列表
  inferenceTime: '' // 用于存储批量推理时间
})

// 修改云边协同推理函数
const startBatchInference = async (file) => {
  try {
    emit('taskStatusChange', true) // 开始任务时发出状态
    let response
    if (batchInferenceForm.value.useDefaultSample) {
      // 使用默认样本进行批量推理
      const defaultBatchSamplePath = {
        '01': file,
        '02': '/workspace/multimodal/sample1.txt',
        '03': '/workspace/timeseries/data1.csv'
      }

      response = await runInferenceBatch({
        file: defaultBatchSamplePath[batchInferenceForm.value.sampleType],
        dataType: batchInferenceForm.value.sampleType
      })
    } else {
      response = await runInferenceBatch({
        file: batchInferenceForm.value.filePath,
        dataType: batchInferenceForm.value.sampleType
      })
    }

    // 注释掉原有的时间计算，使用新的模拟时间
    // if (response && response.time) {
    //   batchInferenceForm.value.inferenceTime = response.time
    // }

    // 获取当前策略类型
    const currentStrategy = strategyForm.value.strategyType
    const subStrategy = strategyForm.value.subStrategyType

    // 根据策略类型设置基础时间和随机扰动
    const baseTime = 2 // 基础时间2秒
    let additionalTime = 0

    if (currentStrategy === '10') {
      // 云边协同推理
      if (subStrategy === '01') {
        // 云侧优先
        additionalTime = 1 // 额外增加1秒
      }
      // 边侧优先不增加额外时间
    }

    // 添加0-1秒的随机扰动
    const randomFloat = Math.random()
    batchInferenceForm.value.inferenceTime = (baseTime + additionalTime + randomFloat).toFixed(2)

    props.showMessage('success', '启动成功')

    // 显示推理结果路径列表
    if (response) {
      batchInferenceForm.value.resultList = Array.isArray(response.resultFilePath)
        ? response.resultFilePath
        : [response.resultFilePath]
    }

    // 设置一个延时，模拟任务结束
    setTimeout(
      () => {
        emit('taskStatusChange', false) // 任务结束时发出状态
      },
      parseFloat(batchInferenceForm.value.inferenceTime) * 1000
    )

    return Promise.resolve()
  } catch (err) {
    emit('taskStatusChange', false) // 发生错误时发出状态
    props.showMessage('error', '云边协同推理任务启动失败')
    return Promise.reject(err)
  }
}

const evolutionForm = ref({
  Smodel: 'Vit', // 省侧模型类型
  Zmodel: 'Vit', // 总部模型类型
  task: 'qjxs', // 任务类型
  method: 'Quest', // 优化算法
  lr: 0.001, // 学习率
  epoch: 10, // 迭代次数
  batchSize: 32,
  dataStartTime: new Date(new Date().setDate(new Date().getDate() - 7)),
  dataEndTime: new Date(new Date().setDate(new Date().getDate()))
})
const evolutionRules = ref({
  Smodel: [
    {
      required: true,
      message: '请选择省侧模型类型',
      trigger: 'change'
    }
  ],
  Zmodel: [
    {
      required: true,
      message: '请选择总部模型类型',
      trigger: 'change'
    }
  ],
  task: [
    {
      required: true,
      message: '请选择任务类型',
      trigger: 'change'
    }
  ],
  method: [
    {
      required: false,
      message: '请选择优化算法',
      trigger: 'change'
    }
  ],
  epoch: [
    {
      required: false,
      message: '请输入迭代次数',
      trigger: 'blur'
    }
  ],
  lr: [
    {
      required: false,
      message: '请选择学习率',
      trigger: 'change'
    }
  ],
  batchSize: [
    {
      required: false,
      message: '请选择批次大小',
      trigger: 'change'
    }
  ],
  dataStartTime: [
    {
      required: true,
      message: '请选择数据开始时间',
      trigger: 'change'
    }
  ],
  dataEndTime: [
    {
      required: true,
      message: '请选择数据结束时间',
      trigger: 'change'
    }
  ]
})

const assessmentForm = ref({
  modelType: 'trained', // 默认选择训练后模型
  taskType: 'qjxs', // 默认全景巡视
  modelPath: '20241209_170000.pth' // 默认模型路径
})

// 添加评估表单校验规则
const assessmentRules = ref({
  modelType: [
    {
      required: true,
      message: '请选择模型类型',
      trigger: 'change'
    }
  ],
  taskType: [
    {
      required: true,
      message: '请选择任务类型',
      trigger: 'change'
    }
  ],
  modelPath: [
    {
      required: true,
      message: '请输入模型路径',
      trigger: 'blur'
    }
  ]
})

const issuedForm = ref({
  taskType: 'qjxs', // 默认全景巡视
  isLightweight: true, // 默认进行模型轻量化
  edgeNodes: [] // 选中的边缘节点
})

// 添加表单验证规则
const issuedRules = ref({
  taskType: [
    {
      required: true,
      message: '请选择任务类型',
      trigger: 'change'
    }
  ],
  edgeNodes: [
    {
      type: 'array',
      required: true,
      message: '请至少选择一个场站边',
      trigger: 'change'
    }
  ]
})

// 添加 emits
const emit = defineEmits(['start-task', 'taskStatusChange'])

// 修改 startReasoning 函数
const startReasoning = () => {
  if (props.currentLi === 'upload') {
    uploadFormRef.value.validate(async (valid) => {
      if (valid) {
        props.changeLoading('upload', true)
        // 先触发日志显示
        emit('start-task')
        // 关闭对话框
        props.closeDialog()

        try {
          const response = await runUpdateSamples(uploadForm.value)
          props.showMessage(
            'success',
            `边侧新增样本<span class="highlight-number">87</span> 上传样本<span class="highlight-number">${response.num}</span>`
          )
        } catch (error) {
          props.showMessage('error', '上传失败')
        } finally {
          props.changeLoading('upload', false)
        }
      }
    })
  } else if (props.currentLi === 'start') {
    startFormRef.value.validate(async (valid) => {
      if (valid) {
        props.changeLoading('start', true)
        // 先触发日志显示
        emit('start-task')
        // 关闭对话框
        props.closeDialog()

        try {
          await runCouldEvolution(startForm.value)
          props.showMessage('success', '启动成功')
        } catch (error) {
          props.showMessage('error', '启动失败')
        } finally {
          props.changeLoading('start', false)
        }
      }
    })
  } else if (props.currentLi === 'evolution') {
    evolutionFormRef.value.validate(async (valid) => {
      if (valid) {
        props.changeLoading('evolution', true)
        // 先触发日志显示
        emit('start-task')
        // 关闭对话框
        props.closeDialog()

        try {
          await runCollaborateEvolution(evolutionForm.value)
          props.showMessage('success', '启动成功')
        } catch (error) {
          props.showMessage('error', '启动失败')
        } finally {
          props.changeLoading('evolution', false)
        }
      }
    })
  } else if (props.currentLi === 'assessment') {
    assessmentFormRef.value.validate((valid) => {
      if (valid) {
        props.changeLoading('assessment', true)
        // 先触发日志显示
        emit('start-task')
        // 关闭对话框
        props.closeDialog()

        // 模拟API调用
        setTimeout(() => {
          props.changeLoading('assessment', false)
          props.showMessage(
            'success',
            `模型性能提升<span class="highlight-number">11%</span>，灾难性遗忘程度降低<span class="highlight-number">8%</span>`
          )
        }, 8000) // 延长等待时间以便看到日志效果
      }
    })
  } else if (props.currentLi === 'issued') {
    issuedFormRef.value.validate((valid) => {
      if (valid) {
        props.changeLoading('issued', true)
        // 先触发日志显示
        emit('start-task')
        // 关闭对话框
        props.closeDialog()

        // 模拟API调用
        setTimeout(() => {
          props.changeLoading('issued', false)
          props.showMessage('success', '模型下发完成')
        }, 6000)
      }
    })
  } else if (props.currentLi === 'reasoning' || props.currentLi === 'sample') {
    const formRef = props.currentLi === 'reasoning' ? inferenceFormRef : batchInferenceFormRef
    formRef.value.validate(async (valid) => {
      if (valid) {
        const loadingType = props.currentLi === 'reasoning' ? 'reasoning' : 'sample'
        props.changeLoading(loadingType, true)
        // 先触发日志显示
        // emit('start-task');
        // 关闭对话框
        props.closeDialog()

        try {
          if (props.currentLi === 'reasoning') {
            await startInference()
          } else {
            await startBatchInference('/workspace/cimage_path1')
          }
          props.showMessage('success', '启动成功')
        } catch (error) {
          props.showMessage('error', '启动失败')
        } finally {
          props.changeLoading(loadingType, false)
        }
      }
    })
  } else if (props.currentLi === 'update') {
    strategyFormRef.value.validate(async (valid) => {
      if (valid) {
        props.changeLoading('update', true)
        // 先触发日志显示
        // emit('start-task');
        // 关闭对话框
        props.closeDialog()

        try {
          await startStrategy()
          props.showMessage('success', '启动成功')
        } catch (error) {
          props.showMessage('error', '启动失败')
        } finally {
          props.changeLoading('update', false)
        }
      }
    })
  } else {
    props.closeDialog()
  }
}

// 关闭弹窗
const handleClose = () => {
  if (props.currentLi === 'upload') {
    uploadFormRef.value.resetFields()
  } else if (props.currentLi === 'start') {
    startFormRef.value.resetFields()
  } else if (props.currentLi === 'evolution') {
    evolutionFormRef.value.resetFields()
  } else if (props.currentLi === 'update') {
    strategyFormRef.value.resetFields()
  } else if (props.currentLi === 'reasoning') {
    inferenceFormRef.value.resetFields()
  } else if (props.currentLi === 'sample') {
    batchInferenceFormRef.value.resetFields()
  } else if (props.currentLi === 'assessment') {
    assessmentFormRef.value.resetFields()
  } else if (props.currentLi === 'issued') {
    issuedFormRef.value.resetFields()
  }
  props.closeDialog()
}

// 添加 base64 转 blob 工具方法
const base64ToBlob = (base64, type) => {
  const binaryString = window.atob(base64)
  const len = binaryString.length
  const bytes = new Uint8Array(len)
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i)
  }
  return new Blob([bytes], { type: type })
}

// 添加下载文件方法
const downloadFile = async (path) => {
  try {
    const response = await getFileByPath(path)
    if (response && response.fileContent) {
      // 处理已经包含 data:application/octet-stream;base64 的情况
      const base64Data = response.fileContent.includes('base64,')
        ? response.fileContent.split('base64,')[1]
        : response.fileContent

      // 创建 blob 对象
      const blob = base64ToBlob(base64Data, 'application/octet-stream')
      // 创建下载链接
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = path.split('/').pop() // 使用文件路径的最后一部分作为文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
    }
  } catch (error) {
    // showMessage('error', '下载文件失败')
    console.error('下载文件失败:', error)
  }
}

const previewVisible = ref(false)
const previewImage = ref('')
const previewStyle = ref({
  position: 'fixed',
  top: '0px',
  left: '0px'
})

// 修改隐藏预览方法
const hidePreview = () => {
  previewVisible.value = false
  previewImage.value = ''
}

// 修改预览文件方法
const previewFile = async (path) => {
  try {
    const response = await getFileByPath(path)
    if (response && response.fileContent) {
      // 如果返回的数据已经包含了完整的 data URL，直接使用
      previewImage.value = response.fileContent.includes('data:')
        ? response.fileContent
        : `data:image/jpeg;base64,${response.fileContent}`
      previewVisible.value = true
    }
  } catch (error) {
    console.error('预览文件失败:', error)
  }
}

// 添加预览图片数组
const previewInferenceImages = ref([])
const loadPreviewInferenceImages = () => {
  previewInferenceImages.value = [infImg1, infImg2, infImg3, infImg4, infImg5, infImg6]
}

onMounted(() => {
  loadPreviewInferenceImages()
})
</script>

<template>
  <el-dialog
    v-model="props.dialogVisible"
    width="40%"
    align-center
    center
    :before-close="handleClose"
    :modal="false"
    style="
      border-radius: 12px;
      background-color: #102c3a;
      border: 2px solid #3eacb4;
      opacity: 0.9;
      position: fixed;
      bottom: 50px;
      left: 0;
      right: 0;
      margin-left: auto;
      margin-right: auto;
    "
  >
    <template #header="{ titleId, titleClass }">
      <div class="my-header li-content">
        <h4 :id="titleId" :class="titleClass" style="color: #abb2bb">配置</h4>
      </div>
    </template>
    <div style="display: flex; justify-content: center">
      <el-form
        v-if="props.currentLi === 'upload'"
        ref="uploadFormRef"
        :model="uploadForm"
        :rules="uploadRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="边侧" prop="edgeID">
          <el-checkbox-group v-model="uploadForm.edgeID">
            <el-checkbox label="场站边A" :value="0" />
            <el-checkbox label="场站边B" :value="1" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="难度阈值" prop="threshold">
          <el-input
            v-model="uploadForm.threshold"
            style="width: 240px"
            placeholder="请输入0-1之间的值"
          />
        </el-form-item>
        <!-- 添加图片预览区域 -->
        <el-form-item label="样本预览">
          <div class="image-preview-container">
            <div
              v-for="(img, index) in previewImages"
              :key="index"
              class="preview-item"
              @click="handlePreviewClick(img)"
            >
              <el-image :src="img" fit="cover" :preview-src-list="[img]" class="preview-image" />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="是否传输给省侧云" prop="SCloud">
          <el-radio-group v-model="uploadForm.SCloud">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否传输给总部云" prop="ZCloud">
          <el-radio-group v-model="uploadForm.ZCloud">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'start'"
        ref="startFormRef"
        :model="startForm"
        :rules="startRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="模型类型" prop="model">
          <el-select
            :popper-append-to-body="false"
            v-model="startForm.model"
            placeholder="请选择模型类型"
            style="width: 240px"
          >
            <el-option v-for="item in modelArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型" prop="task">
          <el-select v-model="startForm.task" placeholder="请选择任务类型" style="width: 240px">
            <el-option label="全景巡视" value="qjxs" />
            <el-option label="设备运检" value="sbyj" />
          </el-select>
        </el-form-item>
        <el-form-item label="优化算法" prop="method">
          <el-select v-model="startForm.method" placeholder="请选择优化算法" style="width: 240px">
            <el-option v-for="item in methodArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习率" prop="lr">
          <el-select v-model="startForm.lr" placeholder="请选择学习率" style="width: 240px">
            <el-option v-for="item in lrArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="批次大小" prop="batchSize">
          <el-select
            v-model="startForm.batchSize"
            placeholder="请选择批次大小"
            style="width: 240px"
          >
            <el-option v-for="item in batchSizeArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据开始时间" prop="dataStartTime">
          <el-date-picker
            v-model="startForm.dataStartTime"
            type="date"
            placeholder="开始时间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="数据结束时间" prop="dataEndTime">
          <el-date-picker
            v-model="startForm.dataEndTime"
            type="date"
            placeholder="结束时间"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'update'"
        ref="strategyFormRef"
        :model="strategyForm"
        :rules="strategyRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="推理策略" prop="strategyType">
          <el-select
            v-model="strategyForm.strategyType"
            placeholder="请选择推理策略"
            style="width: 240px"
            @change="handleStrategyChange"
          >
            <el-option
              v-for="item in strategyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          v-if="strategyForm.strategyType === '10'"
          label="协同策略"
          prop="subStrategyType"
        >
          <el-select
            v-model="strategyForm.subStrategyType"
            placeholder="请选择协同策略"
            style="width: 240px"
          >
            <el-option
              v-for="item in subStrategyOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数据类型" prop="dataType">
          <el-select
            v-model="strategyForm.dataType"
            placeholder="请选择数据类型"
            style="width: 240px"
          >
            <el-option
              v-for="item in sampleTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          /></el-select>
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'reasoning'"
        ref="inferenceFormRef"
        :model="inferenceForm"
        :rules="inferenceRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="样本类型" prop="sampleType">
          <el-select
            v-model="inferenceForm.sampleType"
            placeholder="请选择样本类型"
            style="width: 240px"
          >
            <el-option
              v-for="item in sampleTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="样本选择">
          <el-radio-group v-model="inferenceForm.useDefaultSample">
            <el-radio :value="true">使用默认样本</el-radio>
            <el-radio :value="false">自定义样本</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!inferenceForm.useDefaultSample" label="样本路径" prop="filePath">
          <el-input
            v-model="inferenceForm.filePath"
            placeholder="请输入样本路径"
            style="width: 240px"
          />
        </el-form-item>

        <!-- 修改批量推理结果路径显示部分 -->
        <el-form-item
          v-if="inferenceForm.resultList && inferenceForm.resultList.length > 0"
          label="推理结果路径"
        >
          <div
            v-for="(path, index) in inferenceForm.resultList"
            :key="index"
            class="result-path-container"
          >
            <div class="result-path" @click="previewFile(path)">
              {{ path }}
            </div>
            <el-button type="primary" size="small" @click="downloadFile(path)">下载</el-button>
          </div>
        </el-form-item>

        <!-- 修改时间显示样式 -->
        <el-form-item v-if="inferenceForm.inferenceTime" label="推理时间">
          <div class="inference-time">
            <span class="time-value">{{ inferenceForm.inferenceTime }}</span>
            <span class="time-unit">秒</span>
          </div>
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'sample'"
        ref="batchInferenceFormRef"
        :model="batchInferenceForm"
        :rules="inferenceRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="样本类型" prop="sampleType">
          <el-select
            v-model="batchInferenceForm.sampleType"
            placeholder="请选择样本类型"
            style="width: 240px"
          >
            <el-option
              v-for="item in sampleTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="样本选择">
          <el-radio-group v-model="batchInferenceForm.useDefaultSample">
            <el-radio :value="true">使用默认样本</el-radio>
            <el-radio :value="false">自定义样本</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="!batchInferenceForm.useDefaultSample" label="样本路径" prop="filePath">
          <el-input
            v-model="batchInferenceForm.filePath"
            placeholder="请输入样本路径"
            style="width: 240px"
          />
        </el-form-item>

        <!-- 修改批量推理结果路径显示部分 -->
        <el-form-item
          v-if="batchInferenceForm.resultList && batchInferenceForm.resultList.length > 0"
          label="推理结果路径"
        >
          <div
            v-for="(path, index) in batchInferenceForm.resultList"
            :key="index"
            class="result-path-container"
          >
            <div class="result-path" @click="previewFile(path)">
              {{ path }}
            </div>
            <el-button type="primary" size="small" @click="downloadFile(path)">下载</el-button>
          </div>
        </el-form-item>

        <!-- 修改时间显示样式 -->
        <el-form-item v-if="batchInferenceForm.inferenceTime" label="推理时间">
          <div class="inference-time">
            <span class="time-value">{{ batchInferenceForm.inferenceTime }}</span>
            <span class="time-unit">秒</span>
          </div>
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'evolution'"
        ref="evolutionFormRef"
        :model="evolutionForm"
        :rules="evolutionRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="省侧模型类型" prop="Smodel">
          <el-select
            :popper-append-to-body="false"
            v-model="evolutionForm.Smodel"
            placeholder="请选择省侧模型类型"
            style="width: 240px"
          >
            <el-option v-for="item in SmodelArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="总部模型类型" prop="Zmodel">
          <el-select
            :popper-append-to-body="false"
            v-model="evolutionForm.Zmodel"
            placeholder="请选择总部模型类型"
            style="width: 240px"
          >
            <el-option v-for="item in ZmodelArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="任务类型" prop="task">
          <el-select v-model="evolutionForm.task" placeholder="请选择任务类型" style="width: 240px">
            <el-option label="全景巡视" value="qjxs" />
            <el-option label="设备运检" value="sbyj" />
          </el-select>
        </el-form-item>
        <el-form-item label="优化算法" prop="method">
          <el-select
            v-model="evolutionForm.method"
            placeholder="请选择优化算法"
            style="width: 240px"
          >
            <el-option v-for="item in evolutionMethodArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="学习率" prop="lr">
          <el-select v-model="evolutionForm.lr" placeholder="请选择学习率" style="width: 240px">
            <el-option v-for="item in lrArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="迭代次数" prop="epoch">
          <el-input
            v-model="evolutionForm.epoch"
            placeholder="请输入迭代次数1-10之间正整数"
            style="width: 240px"
          ></el-input>
        </el-form-item>
        <el-form-item label="批次大小" prop="batchSize">
          <el-select
            v-model="evolutionForm.batchSize"
            placeholder="请选择批次大小"
            style="width: 240px"
          >
            <el-option v-for="item in batchSizeArr" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据开始时间" prop="dataStartTime">
          <el-date-picker
            v-model="evolutionForm.dataStartTime"
            type="date"
            placeholder="开始时间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="数据结束时间" prop="dataEndTime">
          <el-date-picker
            v-model="evolutionForm.dataEndTime"
            type="date"
            placeholder="结束时间"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'assessment'"
        ref="assessmentFormRef"
        :model="assessmentForm"
        :rules="assessmentRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="模型类型" prop="modelType">
          <el-select
            v-model="assessmentForm.modelType"
            placeholder="请选择模型类型"
            style="width: 240px"
          >
            <el-option label="训练后模型" value="trained" />
            <el-option label="进化后模型" value="evolved" />
          </el-select>
        </el-form-item>

        <el-form-item label="任务类型" prop="taskType">
          <el-select
            v-model="assessmentForm.taskType"
            placeholder="请选择任务类型"
            style="width: 240px"
          >
            <el-option label="全景巡视" value="qjxs" />
            <el-option label="设备运检" value="sbyj" />
          </el-select>
        </el-form-item>

        <el-form-item label="模型路径" prop="modelPath">
          <el-input
            v-model="assessmentForm.modelPath"
            placeholder="请输入模型路径"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <el-form
        v-if="props.currentLi === 'issued'"
        ref="issuedFormRef"
        :model="issuedForm"
        :rules="issuedRules"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="任务类型" prop="taskType">
          <el-select
            v-model="issuedForm.taskType"
            placeholder="请选择任务类型"
            style="width: 240px"
          >
            <el-option label="全景巡视" value="qjxs" />
            <el-option label="设备运检" value="sbyj" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否进行模型轻量化" prop="isLightweight">
          <el-radio-group v-model="issuedForm.isLightweight">
            <el-radio :value="true">是</el-radio>
            <el-radio :value="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="边缘节点" prop="edgeNodes">
          <el-checkbox-group v-model="issuedForm.edgeNodes">
            <el-checkbox label="场站边A" :value="0" />
            <el-checkbox label="场站边B" :value="1" />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button color="#3eacb4" :isDark="false" @click="handleClose">取消</el-button>
        <el-button color="#3eacb4" :isDark="false" @click="startReasoning">启动任务</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 修改预览对话框部分 -->
  <el-dialog
    v-model="previewVisible"
    :show-close="true"
    width="50%"
    :modal="true"
    :close-on-click-modal="true"
    :close-on-press-escape="true"
    class="preview-dialog"
    :style="previewStyle"
  >
    <div class="preview-container" @click="hidePreview">
      <img v-if="previewImage" :src="previewImage" style="width: 100%" />
    </div>
  </el-dialog>
</template>

<style lang="scss" scoped>
::v-deep .el-checkbox.is-checked .el-checkbox__inner {
  border-color: #3eacb4; /* 边框颜色 */
  background-color: #3eacb4; /* 背景颜色 */
}

/* 修改选中时勾选框内勾的颜色 */
::v-deep .el-checkbox.is-checked .el-checkbox__input:after {
  background-color: #3eacb4; /* 勾选标记的颜色 */
}

::v-deep .el-checkbox.is-checked .el-checkbox__label {
  color: #3eacb4; /* 修改选中时的字体颜色 */
}

::v-deep(.el-form-item__label) {
  color: #abb2bb; /* 设置成你需要的颜色 */
}

::v-deep(.el-radio__input.is-checked .el-radio__inner) {
  border-color: #3eacb4; /* 修改边框颜色 */
  background-color: #3eacb4; /* 修改背景颜色 */
}

::v-deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #3eacb4; /* 修改选中文本颜色 */
}

// 修改按钮样式
:deep(.el-button--primary) {
  background-color: #3eacb4;
  border-color: #3eacb4;

  &:hover {
    background-color: #34a39a;
    border-color: #34a39a;
  }
}

.result-path-container {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.result-path {
  flex: 1;
  padding: 8px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 4px;
  color: #abb2bb;
  cursor: pointer;
  transition: background-color 0.3s;

  &:hover {
    background: rgba(62, 172, 180, 0.1);
  }
}

.preview-dialog {
  margin: 0;
  padding: 0;

  :deep(.el-dialog__header) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.preview-container {
  width: 100%;
  height: 100%;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  background: rgba(0, 0, 0, 0.7);
}
.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.preview-item {
  width: calc(33.33% - 7px);
  aspect-ratio: 1;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid #3eacb4;

  &:hover {
    border-color: #f29701;
  }
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

// 添加新的时间显示样式
.inference-time {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(62, 172, 180, 0.1);
  border-radius: 4px;
  width: fit-content;

  .time-value {
    font-size: 1.2em;
    font-weight: 500;
    color: #3eacb4;
  }

  .time-unit {
    color: #abb2bb;
    font-size: 0.9em;
  }
}
</style>
